package top.zhangjianyong.tools.reptile;

import top.zhangjianyong.tools.utils.RegexUtil;
import top.zhangjianyong.tools.utils.UUIDUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * @author ： zhangjianyong
 * @date ： 2023/3/22 10:52 AM
 */
public class UrlUtil {

    /**
     * 获取http协议
     *
     * @param url
     * @return
     */
    public static String protocol(String url) {
        String regex = "(http.?):";
        return RegexUtil.matcherFirst(url, regex, 1);
    }

    /**
     * 获取域名
     *
     * @param url
     * @return
     */
    public static String host(String url) {
        String regex = "http.?://([^/]*)";
        return RegexUtil.matcherFirst(url, regex, 1);
    }


    public static String prefix(String url) throws UnsupportedEncodingException {
        url = URLDecoder.decode(url, Charset.defaultCharset().name());
        if (url.contains("?")) {
            int i = url.indexOf("?");
            url = url.substring(0, i);
        }

        String regex = "(http.?://.*)/";
        return RegexUtil.matcherFirst(url,regex,1);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String url = "https://hao123-static.cdn.bcebos.com/manual-res/www-data-extend/redian/sheshouyef.htm";
        String prefix = prefix(url);
        System.out.println(prefix);
    }


    public static String getUrl(String location, String url) {
        if (location.startsWith("http")) {
            return location;
        }
        if (location.startsWith("/")) {
            return protocol(url) + "://" + host(url) + location;
        } else {
            return protocol(url) + "://" + host(url) + "/" + location;
        }
    }


}
